<script setup>
  import { message, ossImg } from "@/utils/utils";
  import { onMounted, reactive } from "vue";
  import { GetPandaVideo, GetSubscribeStatus } from "@/services/activity";
  import { onHide, onLoad, onShareAppMessage, onShow, onUnload } from "@dcloudio/uni-app";
  import { Subscribe } from "@/services/utils";


  const emdlz = getApp().emdlz

  const state = reactive({
    status: 0, // 0生成中；1已生成
    vid: '',
    isSubscribe: false,
    toIndex: false
  })

  const videoInfo = reactive({})

  let enterTime = "";
  let outTime = "";
  let stayTime = "";

  onShow(async () => {
    enterTime = new Date();
    state.vid && getVideoInfo()
  })

  onHide(() => {
    // 用户退出时间
    outTime = new Date();
    //停留时间(毫秒)
    stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
    if (!state.status) {
      emdlz('track','event','Oreo_24panda_homepage','view','video_loading', stayTime);
    } else {
      emdlz('track','event','Oreo_24panda_homepage','view','video_action', stayTime);
    }
  })

  let infoTimer = null

  onMounted(() => {
    infoTimer = setInterval(() => getVideoInfo(), 30000)
  })

  onUnload(() => {
    clearInterval(infoTimer)
    // 用户退出时间
    outTime = new Date();
    //停留时间(毫秒)
    stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
    if (!state.status) {
      emdlz('track','event','Oreo_24panda_homepage','view','video_loading', stayTime);
    } else {
      emdlz('track','event','Oreo_24panda_homepage','view','video_action', stayTime);
    }
  })

  onLoad(async ({ vid, toIndex }) => {
    state.vid = vid
    console.log('toIndex', toIndex)
    if (toIndex) state.toIndex = true
    GetSubscribeStatus({
      appId: process.env.WXAPPID,
      scene: 'PANDA_VIDEO_COMPLETE_NOTIFY',
      thirdPartyId: vid
    }).then(({ data }) => {
      state.isSubscribe = data
    })
  })

  const getVideoInfo = async () => {
    const { data } = await GetPandaVideo(state.vid)
    Object.assign(videoInfo, data || {})
    state.status = data?.status
    if (data?.status) clearInterval(infoTimer)
  }

  const handleSaveVideo = () => {
    emdlz('track','event','Oreo_24panda_homepage','click','save_video','');
    uni.showLoading({ title: '正在保存中..' })
    uni.downloadFile({
      url: videoInfo.url,
      success: ({ tempFilePath }) => {
        uni.saveVideoToPhotosAlbum({
          filePath: tempFilePath,
          success: () => {
            uni.showToast({ title: '保存成功', icon: 'success' })
          }
        })
      },
      fail: () => {
        uni.hideLoading()
        uni.showToast({ icon: "error", title: '保存失败' })
      },
      complete: () => uni.hideLoading()
    })
  }

  const toWall = () => {
    emdlz('track','event','Oreo_24panda_homepage','click','wall_button','');
    uni.navigateTo({
      url: `/campaign/pages/panda2024/index?wall=1`
    })
  }

  const handleBack = () => {
    emdlz('track','event','Oreo_24panda_homepage','click','back_last','');

    const firstPage = getCurrentPages()?.at(-2)?.route

    setTimeout(() => {
      if (state.toIndex) return uni.redirectTo({ url: '/campaign/pages/panda2024/index' })
      firstPage === 'pages/loading/loading' ?
        uni.switchTab({ url: '/pages/home/home'}) :
        uni.navigateBack()
    })
  }

  const handleSubscribeMessage = () => {
    if (state.isSubscribe) return
    emdlz('track','event','Oreo_24panda_homepage','click','subscrip_campaign','');
    /**
     * 	测试环境模版id：H9gXsw7DzoXX5FW7C3Qgfh25vRYiFMt-FGJb_dxu_O8
     * 	正式环境模版id：nhMrOYgtEMuMjWwrN6WC8_8NXV-amneKNjvAlMFY0ls
     */
    uni.requestSubscribeMessage({
      tmplIds: ['nhMrOYgtEMuMjWwrN6WC8_8NXV-amneKNjvAlMFY0ls'],
      success: async (result) => {
        await Subscribe({
          appId: process.env.WXAPPID,
          scene: ["PANDA_VIDEO_COMPLETE_NOTIFY"],
          thirdPartyId: state.vid
        });
        state.isSubscribe = true
        message('消息订阅成功')
      },
      fail: console.log,
    });
  }

  const handlePlayAgain = () => {
    emdlz('track','event','Oreo_24panda_homepage','click','one_more','');
    setTimeout(() => uni.navigateTo({
      url: `/campaign/pages/panda2024/index`
    }))
  }

  onShareAppMessage(() => {
    return {
      title: '奥利奥拍了拍你，参与赢大奖',
      imageUrl: ossImg('others/2024panda/panda_share.jpg'),
      path: `/campaign/pages/panda2024/index?scene=KJTW0Z22ZTUZUXTIKZCR7FR4V0`
    }
  })
</script>

<template>
  <view
    class="video-page"
    :style="{ backgroundImage: `url(${ossImg('others/2024panda/index.png')})` }"
  >
    <image
      class="w-120px h-48px mt-55px"
      :src="ossImg('others/2024panda/oreo_logo.png')"
    ></image>
    <view
      class="video-box"
      :class="{
        success: state.status,
        'mt-18px': !state.status,
        'mt-4px': state.status,
      }"
      :style="{ backgroundImage: `url(${state.status ? ossImg('others/2024panda/sp_bg2.png') : ossImg('others/2024panda/sp_bg.png')})` }"
    >
      <view class="loading-gif mt-206px" v-if="!state.status">
        <image
          class="w-176px h-8px"
          :src="ossImg('others/2024panda/loading.gif')"
        ></image>
        <text>{{ (videoInfo.delayTime / 60).toFixed(0) }}</text>
      </view>

      <view
        v-else
        class="video mt-56px"
      >
        <video
          id="myVideo"
          :src="videoInfo.url"
          :show-bottom-progress="false"
          controls
        ></video>
      </view>
    </view>
    <view class="video-action mt-13px">
      <template v-if="!state.status">
        <image
          class="w-160px h-63px mr-3px"
          :src="state.isSubscribe ? ossImg('others/2024panda/button2_1.png') : ossImg('others/2024panda/button2.png')"
          @click.stop="handleSubscribeMessage"
        ></image>
        <image
          class="w-155px h-63px"
          :src="ossImg('others/2024panda/button1.png')"
          @click.stop="toWall"
        ></image>
      </template>
      <template v-else>
        <image
          class="w-160px h-63px mr-3px"
          :src="ossImg('others/2024panda/button3.png')"
          @click.stop="handleSaveVideo"
        ></image>
        <image
          class="w-155px h-63px"
          :src="ossImg('others/2024panda/button4.png')"
          @click.stop="handlePlayAgain"
        ></image>
      </template>
    </view>

    <image v-if="state.status" class="w-235px h-12px mb-10px" :src="ossImg('others/2024panda/video_tips.png')" />

    <image
      class="w-39px h-55px fixed left-27px top-70px"
      :src="ossImg('others/2024panda/back_icon.png')"
      @click.stop="handleBack"
    ></image>
  </view>
</template>

<style lang="scss" scoped>
  .loading-gif {
    color: white;
    font-size: 20px;
    font-weight: bold;
    line-height: 1;
    position: relative;
    text {
      position: absolute;
      right: 65px;
      top: 31.5px;
    }
  }
  .video-page {
    width: 100%;
    height: 100vh;
    background-position: top left;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    .video-box {
      width: 280px;
      height: 445px;
      background-position: top left;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      position: relative;
      &.success {
        width: 267px;
        height: 480px;
        //&::after {
        //  content: "";
        //  width: inherit;
        //  height: inherit;
        //  background-position: top left;
        //  background-repeat: no-repeat;
        //  background-size: 100% 100%;
        //  background-image: inherit;
        //  position: absolute;
        //  z-index: 1;
        //  top: 0;
        //  left: 0;
        //}
      }
      .video {
        width: 229px;
        height: 405px;
        position: relative;
        z-index: 0;
        video {
          width: inherit;
          height: inherit;
          border-radius: 7px;
        }
      }
    }
  }
</style>
